// 驱动管理器实现

use thiserror::Error;
use super::super::exokernel::api;
use super::super::exokernel::capability::ThreadSafeCapability;
use super::super::core::types::DriverId;

// 定义驱动错误类型
#[derive(Error, Debug)]
pub enum DriverError {
    #[error("Driver registration failed")]
    RegistrationFailed,
    
    #[error("Driver unregistration failed")]
    UnregistrationFailed,
    
    #[error("Driver initialization failed")]
    InitializationFailed,
    
    #[error("Driver operation failed")]
    OperationFailed,
    
    #[error("Invalid driver capability")]
    InvalidCapability,
    
    #[error("Invalid driver ID")]
    InvalidDriverId,
    
    #[error("Invalid driver name")]
    InvalidDriverName,
    
    #[error("Invalid driver entry point")]
    InvalidEntryPoint,
}

// 定义驱动结果类型
pub type DriverResult<T> = Result<T, DriverError>;

// 驱动管理器
pub struct DriverManager {
    capability: ThreadSafeCapability,
}

impl DriverManager {
    // 创建新的驱动管理器
    pub fn new(capability: ThreadSafeCapability) -> DriverResult<Self> {
        // 验证能力是否为驱动管理器类型
        if let Err(_) = capability.lock() {
            return Err(DriverError::InvalidCapability);
        }
        
        Ok(DriverManager {
            capability,
        })
    }
    
    // 注册驱动
    pub fn register_driver(&self, name: &str, entry_point: u64) -> DriverResult<DriverId> {
        // 验证驱动名称是否有效
        if name.is_empty() || name.len() > 128 {
            return Err(DriverError::InvalidDriverName);
        }
        
        // 验证入口点是否有效
        if entry_point == 0 {
            return Err(DriverError::InvalidEntryPoint);
        }
        
        // 获取能力ID
        // 注意：由于我们现在使用exokernel_device_register，不再需要cap_id参数
        let _cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(DriverError::RegistrationFailed);
        };
        
        // 调用FFI注册驱动
        let driver_id = unsafe {
            api::exokernel_device_register(name.as_ptr() as *mut u8)
        };
        
        if driver_id != 0 {
            Ok(driver_id)
        } else {
            Err(DriverError::RegistrationFailed)
        }
    }
    
    // 注销驱动
    pub fn unregister_driver(&self, driver_id: DriverId) -> DriverResult<bool> {
        // 验证驱动ID是否有效
        if driver_id == 0 {
            return Err(DriverError::InvalidDriverId);
        }
        
        // 获取能力ID
        // 注意：由于我们现在使用exokernel_device_remove，不再需要cap_id参数
        let _cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(DriverError::UnregistrationFailed);
        };
        
        // 调用FFI注销驱动
        unsafe {
            api::exokernel_device_remove(driver_id);
        }
        
        // 对于没有返回值的函数，我们假设它成功执行
        Ok(true)
    }
    
    // 初始化驱动
    pub fn init_driver(&self, driver_id: DriverId) -> DriverResult<bool> {
        // 验证驱动ID是否有效
        if driver_id == 0 {
            return Err(DriverError::InvalidDriverId);
        }
        
        // 获取能力ID
        // 注意：由于我们现在使用exokernel_driver_load，不再需要cap_id参数
        let _cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(DriverError::InitializationFailed);
        };
        
        // 调用FFI初始化驱动
        let result = unsafe {
            // 将driver_id转换为指针
            let driver_ptr = driver_id as *mut u8;
            api::exokernel_driver_load(driver_ptr)
        };
        
        if result {
            Ok(true)
        } else {
            Err(DriverError::InitializationFailed)
        }
    }
    
    // 向驱动发送命令
    pub fn send_command(&self, driver_id: DriverId, command: u32, data: *const u8, data_size: u32) -> DriverResult<bool> {
        // 验证驱动ID是否有效
        if driver_id == 0 {
            return Err(DriverError::InvalidDriverId);
        }
        
        // 获取能力ID
        // 注意：由于我们现在使用exokernel_device_ioctl，不再需要cap_id参数
        let _cap_id = if let Ok(cap) = self.capability.lock() {
            cap.id()
        } else {
            return Err(DriverError::OperationFailed);
        };
        
        // 调用FFI向驱动发送命令
        let result = unsafe {
            // 将const指针转换为mut指针以符合API要求
            let data_mut_ptr = data as *mut u8;
            api::exokernel_device_ioctl(driver_id, command, data_mut_ptr, data_size as u64) != -1
        };
        
        if result {
            Ok(true)
        } else {
            Err(DriverError::OperationFailed)
        }
    }
}